const { parse } = require('json2csv');
const fs = require('fs');
const iconv = require('iconv-lite');
// 日志打印输出
const { log } = require('./util/log');

// let fileName = '2020_02_23_03_11_03_2020_02_22_10_58_56';
// { "UserID": 640430, "GameID": 1669101, "NickName": "飞羽", "RemarkNickName": "", "UserLv": 1, "IsPartner": 0, "Nullity": 0, "FriendCircleCount": 0, "UpperGameID": 0, "LastLogonType": 0, "AllowMatchScore": 0, "AllowDisGame": 0, "IsAuditors": 0 }
// {"GameNum":"852222118195188","RoomNum":805591,"UserID_1":209908,"GameID_1":4480959,"WinScore_1":55,"UserName_1":"拾月书店","isWinner_1":1,"isOwner_1":1,"UserID_2":152083,"GameID_2":1941611,"WinScore_2":-10,"UserName_2":"峰","isWinner_2":0,"isOwner_2":0,"UserID_3":836910,"GameID_3":1289046,"WinScore_3":-22,"UserName_3":"松波","isWinner_3":0,"isOwner_3":0,"UserID_4":789600,"GameID_4":901092,"WinScore_4":-23,"UserName_4":"朋友","isWinner_4":0,"isOwner_4":0,"PlayCount":8,"GameCount":0,"GameType":2,"WriteDate":"2020-02-22 15:55:03"}

// 恐龙房间
function sortGameList(userlist, gamelist, fileName, res) {
  // 获取简单的 userlist
  let simpleUserlist = [];
  userlist.forEach(item => {
    const { UserID, NickName } = item;
    let score = '0',
      finalScore = 0,
      origin = [],
      totalWinner = [];
    simpleUserlist.push({
      UserID,
      NickName,
      score,
      finalScore,
      origin,
      totalWinner
    });
  });
  // console.log(simpleUserlist)

  // 常量定义
  const MULTIPLE = 1; // 倍数
  const ROOM_FEE = 6; // 房费
  const ROOM_FEE_1 = ROOM_FEE / 1; // 房费
  const ROOM_FEE_2 = ROOM_FEE / 2; // 房费
  const ROOM_FEE_3 = ROOM_FEE / 3; // 房费
  const ROOM_FEE_4 = ROOM_FEE / 4; // 房费
  const ROOM_FEE_FROM = 10; // 房费起征点

  // 统计数据
  gamelist.forEach(item => {
    const {
      UserID_1,
      WinScore_1,
      isWinner_1,
      UserID_2,
      WinScore_2,
      isWinner_2,
      UserID_3,
      WinScore_3,
      isWinner_3,
      UserID_4,
      WinScore_4,
      isWinner_4
    } = item;
    // 整理数据
    // 1.获取 大赢家 数量
    let totalWinner = isWinner_1 + isWinner_2 + isWinner_3 + isWinner_4;
    let fee =
      totalWinner == 2
        ? ROOM_FEE_2
        : totalWinner == 3
        ? ROOM_FEE_3
        : totalWinner == 4
        ? ROOM_FEE_4
        : ROOM_FEE_1;
    // 2.循环 更新数据
    simpleUserlist.forEach(item => {
      if (item.UserID == UserID_1) {
        // 判断是否 大赢家
        if (isWinner_1) {
          if (WinScore_1 <= ROOM_FEE_FROM && WinScore_1 >= 0) fee = 0; // 赢钱 小于 ROOM_FEE_FROM 不交房费
          let number = MULTIPLE * WinScore_1 - fee;
          item.score += parseNumber(number);
          item.finalScore += Number(number);
          item.origin.push(`${WinScore_1}`);
        } else {
          item.score += parseNumber(MULTIPLE * WinScore_1);
          item.finalScore += Number(MULTIPLE * WinScore_1);
          item.origin.push(`${WinScore_1}`);
        }
        item.totalWinner.push(totalWinner);
      } else if (item.UserID == UserID_2) {
        // 判断是否 大赢家
        if (isWinner_2) {
          if (WinScore_2 <= ROOM_FEE_FROM && WinScore_2 >= 0) fee = 0; // 赢钱 小于 ROOM_FEE_FROM 不交房费
          let number = MULTIPLE * WinScore_2 - fee;
          item.score += parseNumber(number);
          item.finalScore += Number(number);
          item.origin.push(`${WinScore_2}`);
        } else {
          item.score += parseNumber(MULTIPLE * WinScore_2);
          item.finalScore += Number(MULTIPLE * WinScore_2);
          item.origin.push(`${WinScore_2}`);
        }
        item.totalWinner.push(totalWinner);
      } else if (item.UserID == UserID_3) {
        // 判断是否 大赢家
        if (isWinner_3) {
          if (WinScore_3 <= ROOM_FEE_FROM && WinScore_3 >= 0) fee = 0; // 赢钱 小于 ROOM_FEE_FROM 不交房费
          let number = MULTIPLE * WinScore_3 - fee;
          item.score += parseNumber(number);
          item.finalScore += Number(number);
          item.origin.push(`${WinScore_3}`);
        } else {
          item.score += parseNumber(MULTIPLE * WinScore_3);
          item.finalScore += Number(MULTIPLE * WinScore_3);
          item.origin.push(`${WinScore_3}`);
        }
        item.totalWinner.push(totalWinner);
      } else if (item.UserID == UserID_4) {
        // 判断是否 大赢家
        if (isWinner_4) {
          if (WinScore_4 <= ROOM_FEE_FROM && WinScore_4 >= 0) fee = 0; // 赢钱 小于 ROOM_FEE_FROM 不交房费
          let number = MULTIPLE * WinScore_4 - fee;
          item.score += parseNumber(number);
          item.finalScore += Number(number);
          item.origin.push(`${WinScore_4}`);
        } else {
          item.score += parseNumber(MULTIPLE * WinScore_4);
          item.finalScore += Number(MULTIPLE * WinScore_4);
          item.origin.push(`${WinScore_4}`);
        }
        item.totalWinner.push(totalWinner);
      }
      // 都没找到
      else;
    });
  });
  // 最后数组排序  finalScore 从高到低
  simpleUserlist.sort((a, b) => {
    return b.finalScore - a.finalScore;
  });
  // 返回前端
  res.end(JSON.stringify(simpleUserlist));
  fs.writeFileSync(`../datalist/fina_${fileName}.json`, JSON.stringify(simpleUserlist));
  // 导出到 csv 格式文件
  const fields = ['UserID', 'NickName', 'finalScore', 'score', 'origin'];
  const opts = { fields };
  try {
    const csv = parse(simpleUserlist, opts);
    // 转编码 为 GBK 解决 csv 中文乱码问题
    var newCsv = iconv.encode(csv, 'GBK');
    fs.writeFileSync(`../datalist/${fileName}.csv`, newCsv);
    log('🍎🍎🍎🍎🍎🍎🍎🍎计算结束🍎🍎🍎🍎🍎🍎🍎🍎');
  } catch (err) {
    console.error(err);
  }
}

// 格式化 数字 为带符号字符串
function parseNumber(number) {
  if (number >= 0) return `+${number}`;
  else return `${number}`;
}

exports.sortGameList = sortGameList;
